<?php
/**
 * Classe de Controle para Emprestimos de itens do Acervo.
 *
 * @author Ruan Carvalho
 */
class LoansController extends AppController {

	var $name = 'Loans';
	
	var $helpers = array('Html', 'Form', 'Js' => array('Jquery'), 'Session', 'Time');
	
	var $components = array('RequestHandler', 'Session');

	/**
	 * 
	 */
	function index() {
		$this->Loan->recursive = 0;
		$this->set('loans', $this->paginate());
	}

	/**
	 * 
	 */
	function add() {
		
		if (!empty($this->data)) {
			
			$this->Loan->create();
			
			//debug($this->data['Copy']);
			
			if ($this->Loan->save($this->data)) {

				foreach ($this->data['Copy'] as $id) {
					
					$this->Loan->Copy->id = $id;
					$this->Loan->Copy->saveField('loaned', 1);
				}
				
				$this->Session->setFlash(__('The loan has been saved', true), 'success.message');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The loan could not be saved. Please, try again.', true), 'error.message');
			}
			
		}

		//$copies = $this->Loan->Copy->find('list');
		$this->set(compact('copies'));
	}

	function view($id = null) {
		
		$total = $this->Loan->find('count');
		
		if ((!$id) || ($id > $total)) {
			$this->Session->setFlash(__('Invalid loan', true), 'success.message');
			$this->redirect(array('action' => 'index'));
		}
		$this->set('loan', $this->Loan->read(null, $id));
	}
	
	function autoComplete() {

		$query = $this->params['url']['term'];

		$people = $this->Loan->Person->find('all', 
			array(
				'conditions' => array('name LIKE' => '%'.$query.'%'),
				'fields' => array('Person.id', 'Person.name'),
				'order' => array('Person.name' => 'ASC')
			)
		);
		$i = 0;
		foreach($people as $person){
			$response[$i]['label'] = $person['Person']['name'];
			$response[$i]['value'] = $person['Person']['id'];
			$i++;
		}

		$this->set('people', $response);
	}
	
	/**
	 * 
	 */
	function devolution() {
			
		if (!empty($this->data)) {
			
			$id = $this->data['Loan']['copy_id'];
			
			$copy = $this->Loan->Copy->find('first', array('conditions' => array('Copy.id' => $id)));
			
			$this->Loan->id = $copy['Loan'][0]['id'];
			
			debug($this->Loan);
			
			$copy = $this->data['Loan']['copy_id'];
			//$user = $this->Auth->user('id');
			
			$copies = null;
			$loans = null;
			
			if ( !empty($copy) ) {
								
				$this->Loan->Copy->id = $copy;
				
				$loanID = $copy['Loan'][0]['id'];
				$loan = $this->Loan->find('first', array(
					'conditions' => array('Loan.id' => $loanID),
					'recursive' => 2
					)
				);
								
				$this->set(compact('loan'));
				$this->set('person', array('Person' => array('name' => 'John Doe')));
			} else {
				$this->Session->setFlash(__('Please, enter a Copy or Person', true), 
					'error.message');
			}
		}
		
		//debug($loan);
	}
}
?>